﻿namespace Plugins.FormicArch.Core
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;

// 异步事件总线
    public class AsyncEventBus
    {
        private readonly Dictionary<Type, List<Delegate>> _handlers = new Dictionary<Type, List<Delegate>>();

        // 订阅事件
        public void SubscribeAsunc<TEvent>(Func<TEvent, Task> handler) where TEvent : IFAEvent
        {
            var eventType = typeof(TEvent);
            if (!_handlers.ContainsKey(eventType))
            {
                _handlers[eventType] = new List<Delegate>();
            }
            _handlers[eventType].Add( handler);
        }

        // 发布事件
        public async Task PublishAsync<TEvent>(TEvent @event) where TEvent : IFAEvent
        {
            var eventType = typeof(TEvent);
            if (_handlers.ContainsKey(eventType))
            {
                var tasks = new List<Task>();
                foreach (var handler in _handlers[eventType])
                {
                    tasks.Add(((Func<TEvent,Task>)handler)(@event));
                }
                await Task.WhenAll(tasks); // 等待所有异步任务完成
            }
        }
        
        // 订阅事件
        public void Subscribe<TEvent>(Action<TEvent> handler) where TEvent : IFAEvent
        {
            var eventType = typeof(TEvent);
            if (!_handlers.ContainsKey(eventType))
            {
                _handlers[eventType] = new List<Delegate>();
            }
            _handlers[eventType].Add( handler);
        }

        // 发布事件
        public  void Publish<TEvent>(TEvent @event) where TEvent : IFAEvent
        {
            var eventType = typeof(TEvent);
            if (_handlers.ContainsKey(eventType))
            {
                var tasks = new List<Task>();
                foreach (var handler in _handlers[eventType])
                {
                    ((Action<TEvent>)handler)(@event);
                }
            }
        }
    }
}
